package edg.db;

import java.sql.Statement;
import java.text.SimpleDateFormat;

public class Logging {
	
	private static final SimpleDateFormat DATETIME =
		new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	/**
	 * Log an error.
	 * @param source Module the error originated in.  Can range from 1 to 4.
	 * @param text Explanation of what went wrong and any other relevant
	 * information needed to track down the issue.
	 * @return Returns true if the error was successfully logged.
	 */
	public static boolean error(int source, String text) {		
		return log("error", source, text);
	}

	/**
	 * Log a message.  Not necessarily an error, but still important information
	 * that you would like tracked for analysis later on.
	 * @param source Module the error originated in.  Can range from 1 to 4.
	 * @param text Explanation of what happened and any other relevant
	 * information.
	 * @return Returns true if the message was successfully logged.
	 */
	public static boolean message(int source, String text) {		
		return log("message", source, text);
	}
	
	private static boolean log(String type, int source, String text) {
		Database.sanitize(text);
		
		if(source < 1 || source > 4) {
			return false;
		}
		
		Statement statement = Database.query(
				
				"INSERT " +
				"INTO errors (type, source, text, timestamp) " +
				"VALUES(" +
					"'" + type + "', " +
					"'" + source + "', " +
					"'" + text + "', " +
					"'" + DATETIME.format(System.currentTimeMillis()) + "');"
					
			);
		
		// See if the query was successful.
		if(statement != null) {
			return true;
		}
		else {
			return false;
		}
	}
	
}